import React, {useContext} from 'react'
import {appSetStateContext} from '../AppState'
import {RobotProps} from './Robot' 

export const withAddToCart = (ChildComponent: React.ComponentType<RobotProps> ) => {
  // 返回类组件
  // return class extends React.Component{}
  // 返回函数式组件
  return (props) => {
    
  // 业务逻辑
  const setState = useContext(appSetStateContext)
  const addToCart = (id, name) => {
    if (setState) {
      setState(state => {
        return {
          ...state,
          shoppingCart: {
            items: [...state.shoppingCart.items, {id, name}]
          }
        }
      })
    }
  }

    // 最终返回为参数传入的ChildComponent
    return <ChildComponent {...props} addToCart={addToCart}></ChildComponent>
  }
}

export const useAddToCart = () => {
  const setState = useContext(appSetStateContext)
  const addToCart = (id, name) => {
    if (setState) {
      setState(state => {
        return {
          ...state,
          shoppingCart: {
            items: [...state.shoppingCart.items, {id, name}]
          }
        }
      })
    }
  }
  return addToCart
}